package com.meta.app;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.meta.api.service.UserServiceQuery;
import com.meta.api.service.UserServiceUpdate;
import com.meta.app.entity.LogEntity;
import com.meta.app.entity.MemberEntity;
import com.meta.app.mapper.LogMapper;
import com.meta.app.service.MemberService;
import com.meta.common.config.WeChatConfig;
import com.meta.common.utils.DateUtil;
import com.meta.common.utils.RegexUtils;
import com.meta.common.utils.SendEmail;
import com.meta.common.utils.UserContext;
import com.meta.common.utils.WeChatUtils;
import com.meta.common.vo.ResponseInfo;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Author: xieZW
 * @Date: 2021/11/21 20:15
 * 小程序入口
 */
@RestController
@RequestMapping("app")
@Slf4j
public class AppController {

    @Autowired
    private UserServiceQuery userServiceQuery;

    @Autowired
    private UserServiceUpdate userServiceUpdate;

    @Autowired
    private MemberService memberService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private LogMapper logMapper;

    /**
     * 最长能输入的内容
     */
    static Integer LongNum = 5000;

    @PostMapping("sendEmail")
    public ResponseInfo get_list(@RequestBody JSONObject jsonObject) {

        UserContext currentContext = UserContext.getCurrentContext();
        System.out.println("currentContext = " + currentContext);

        //核对参数是否正确
        System.out.println("jsonObject = " + jsonObject);
        String msg = (String) jsonObject.get("msg");
        String email = (String) jsonObject.get("email");
        String token = (String) jsonObject.get("token");

        if (token == null) {
            return ResponseInfo.errorWX("获取用户信息失败，请重新登录！");
        }

        if (!RegexUtils.checkEmail(email)) {
            return ResponseInfo.errorWX("请核对邮箱！");
        }
        if (StringUtils.isEmpty(msg)) {
            return ResponseInfo.errorWX("请勇敢说出来！");
        }
        if (msg.length() > LongNum) {
            return ResponseInfo.errorWX("你是个话痨吗！");
        }

        //日志里面记录一下谁使用过这个功能，方便追溯
        LogEntity logEntity = new LogEntity();
        logEntity.setDate(DateUtil.mysqlTimestamp());
        JSONObject o = (JSONObject) redisTemplate.opsForValue().get(token);
        String content = email + "_____________ " + msg + "_______________" + o;
        logEntity.setContent(content);
        logMapper.insertInfo(logEntity);

        //redis 控制 这个功能是否可用 安全控制
        Object xiaochengxufasongyoujian = redisTemplate.opsForValue().get("jinzhifayoujian");
        if (xiaochengxufasongyoujian == null) {
            Object jintianfaleduoshaoci = redisTemplate.opsForValue().get("jintianfaleduoshaoci");
            if (jintianfaleduoshaoci == null) {
                redisTemplate.opsForValue().set("jintianfaleduoshaoci", 1, 24 * 60 * 60, TimeUnit.SECONDS);
            } else {
                Integer count = (Integer) jintianfaleduoshaoci;
                if (count > 10) {
                    return ResponseInfo.errorWX("我累了，等会儿再来找我传话！");
                }
                redisTemplate.opsForValue().set("jintianfaleduoshaoci", count + 1, 24 * 60 * 60, TimeUnit.SECONDS);
            }
            SendEmail.sendQQEmail(msg, email, "TA有话对你说");
        } else {
            return ResponseInfo.errorWX("我累了，等会儿再来找我传话！");
        }
        return ResponseInfo.succWX("发送成功！");
    }


    @PostMapping("/wx_login")
    public ResponseInfo wx_login(@RequestBody MemberEntity param) {
        try {
            log.info("wx_login");
            String code = param.getCode();
            //微信的配置信息
            JSONObject weChatUserInfo = WeChatUtils.findSessionKey(WeChatConfig.getAppId(), WeChatConfig.getAppSecret(), code);
            String unionid = weChatUserInfo.getString("unionid");
            unionid = unionid != null ? unionid : weChatUserInfo.getString("openid");

//            String unionid = "ocSHz4gsncqbttD_jUjv8FEHdd3A";
            MemberEntity user = memberService.findUser(unionid);

            if (user == null) {
                //注册
                param.setUnionId(unionid);
                param.setRegisterDate(DateUtil.mysqlTimestamp());
                this.register(param);
                user = memberService.findUser(unionid);
            }
            log.info("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
            return getResponseInfo(user);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResponseInfo.errorWX(e.getMessage());
        }
    }

    public void register(MemberEntity entity) {
        memberService.addUser(entity);
    }

    @GetMapping("ecs/getServerInfo")
    public ResponseInfo fun01() {

        return ResponseInfo.succ("哈哈哈！");
    }


    /**
     * 登录
     */
    private ResponseInfo getResponseInfo(MemberEntity oneUser) {

        log.info("开始返回登录数据");
        String userId = oneUser.getId().toString();
        // 小程序token
        JSONObject responseDate = new JSONObject();
        String sessionId = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set(sessionId, oneUser, 7200);
        responseDate.put("token", sessionId);
        responseDate.put("unionId", oneUser.getUnionId());
        responseDate.put("userId", userId);
        responseDate.put("pointsNum", oneUser.getPointsNum());
        responseDate.put("registerDate", oneUser.getRegisterDate());
        responseDate.put("corpId", oneUser.getCorpId() == null ? null : oneUser.getCorpId());

        //token有效期是24小时
        redisTemplate.opsForValue().set(sessionId, responseDate, 24 * 60 * 60, TimeUnit.SECONDS);

        return ResponseInfo.succWX(responseDate);
    }

}
